﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using TrafficWatcher.ViewModels;
using TrafficWatcher.Views.Helpers;
using TrafficWatcher.Views.Helpers.TimeVisualizers;

namespace TrafficWatcher.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool DestroyIcon(IntPtr hIcon);

        private readonly MainViewModel mainViewModel;
        private readonly ITimeVisualizer iconImageGenerator = new SquareVisualizer();


        private IntPtr hIcon = IntPtr.Zero;
        private NotifyIcon notifyIcon;

        private ToolStripItem openDirectionMenuItem;

        public MainWindow()
        {
            InitializeComponent();

            mainViewModel = ViewModelLocator.MainStatic;

            CreateNotifyIcon();
        }

        private void CreateNotifyIcon()
        {
            notifyIcon = new NotifyIcon
                {
                    ContextMenuStrip = new ContextMenuStrip
                        {
                            Items =
                                {
                                    new ToolStripMenuItem("Open Direction", null, (_, __) => mainViewModel.OpenDirectionCommand.Execute(null)),
                                    new ToolStripSeparator(),
                                    new ToolStripMenuItem("Settings...", null, (_, __) => mainViewModel.OpenSettingsCommand.Execute(null)),
                                    new ToolStripMenuItem("Exit", null, (_, __) => mainViewModel.ExitCommand.Execute(null))
                                }
                        },
                    Visible = true
                };

            openDirectionMenuItem = notifyIcon.ContextMenuStrip.Items[0];

            notifyIcon.MouseClick += (_, args) => { if (args.Button == MouseButtons.Left) mainViewModel.OpenDirectionCommand.Execute(null); };

            mainViewModel.PropertyChanged += (_, args) =>
                {
                    if (args.PropertyName == "CurrentDirectionsProviderName") SetOpenDirectionMenuItemIcon(mainViewModel.CurrentDirectionsProviderName);
                    else if (args.PropertyName == "Duration") SetIconAndTooltip(mainViewModel.Duration);
                };

            SetOpenDirectionMenuItemIcon(mainViewModel.CurrentDirectionsProviderName);
            SetIconAndTooltip(mainViewModel.Duration);
        }

        private void SetIconAndTooltip(TimeSpan duration)
        {
            var tooltip = DurationLocalizer.ToString(duration);

            using (var image = iconImageGenerator.GenerateImage(duration))
            {
                if (hIcon != IntPtr.Zero)
                {
                    DestroyIcon(hIcon);
                }
                hIcon = image.GetHicon();

                var oldIcon = notifyIcon.Icon;
                notifyIcon.Icon = System.Drawing.Icon.FromHandle(hIcon);
                if (oldIcon != null)
                {
                    oldIcon.Dispose();
                }

                notifyIcon.Text = tooltip;
            }
        }

        private void SetOpenDirectionMenuItemIcon(string providerName)
        {
            var rs = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true).Cast<DictionaryEntry>();
            var image = (from r in rs where r.Value is Icon && providerName.StartsWith((string) r.Key) select r.Value).FirstOrDefault();
            openDirectionMenuItem.Image = (image != null) ? ((Icon)image).ToBitmap() : null;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            notifyIcon.Dispose();
            base.OnClosing(e);
        }
    }
}
